package com.cs2.volunteerpostbackend.service.impl;

import com.cs2.volunteerpostbackend.po.Moment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailService {

    private final JavaMailSender mailSender;
    
    @Value("${spring.mail.username}")
    private String mailUsername;

    @Autowired
    public EmailService(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    /**
     * 处理发送邮件队列中的动态消息（模拟方法）
     * @param moment 动态对象
     */
    public void sendEmailWithMoment(Moment moment) {
        System.out.println("接收到需要发送邮件的动态: " + moment.getTitle());
        System.out.println("动态内容: " + moment.getContent());
        // 实现实际的邮件发送逻辑
        processEmailSending(moment);
    }

    /**
     * 处理邮件发送的具体逻辑
     * @param moment 动态对象
     */
    private void processEmailSending(Moment moment) {
        try {
            // 创建邮件消息
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(mailUsername);
            // 临时借用posterId字段存储收件人邮箱
            message.setTo(moment.getPosterId());
            message.setSubject("新动态：" + moment.getTitle());
            message.setText(moment.getContent());
            
            // 发送邮件
            mailSender.send(message);
            System.out.println("邮件发送成功！");
        } catch (Exception e) {
            System.err.println("邮件发送失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}